package com.app.qbake.module.login;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;

import com.app.qbake.R;
import com.app.qbake.module.login.di.LoginComponent;
import com.app.qbake.module.login.event.LoginSuccessEvent;
import com.app.qbake.module.login.layout.GetCodeLayout;
import com.app.qbake.module.login.mvp.LoginView;
import com.app.qbake.module.login.presenter.LoginPresenter;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nim.uikit.common.util.log.LogUtil;
import com.netease.nim.uikit.config.DemoCache;
import com.netease.nim.uikit.config.preference.Preferences;
import com.netease.nim.uikit.config.preference.UserPreferences;
import com.netease.nimlib.sdk.AbortableFuture;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.StatusBarNotificationConfig;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.wind.base.bean.User;
import com.wind.base.mvp.view.DaggerMvpFragment;
import com.wind.base.repo.UserRepo;
import com.wind.base.request.BaseRequest;
import com.wind.base.utils.ActivityUtil;
import com.wind.base.utils.Md5Util;
import com.wind.coder.annotations.Api;
import com.wind.coder.annotations.Heros;
import com.wind.coder.annotations.Param;
import com.wind.data.login.LoginRequest;
import com.wind.data.login.LoginResponse;
import com.wind.toastlib.ToastUtil;
import com.wind.view.CountdownLayout;
import com.wind.view.PhoneInputView;
import com.wind.view.ValidateEditText;

import org.greenrobot.eventbus.EventBus;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;


@Heros(
        param = @Param(
                viewCanonicalName = "com.app.qbake.module.login.mvp.LoginView",
                responseCanonicalName = "com.wind.data.login.LoginResponse",
                requestCanonicalName = "com.wind.data.login.LoginRequest"

        ),
        api = @Api(httpMethod = Api.HttpMethod.POST, url = "mobileLogin")
)
public class LoginFragment extends DaggerMvpFragment<LoginView,LoginPresenter, LoginComponent>
implements LoginView, GetCodeLayout.OnGetCodeListener {


    @Inject
    LoginPresenter loginPresenter;
    @BindView(R.id.layout_countdown)
    CountdownLayout layout_countdown;
    @BindView(R.id.layout_phone)
    PhoneInputView layout_phone;
    @BindView(R.id.et_code)
    ValidateEditText et_code;
    GetCodeLayout mGetCodeLayout;
    @Override
    protected int getLayoutRes() {
        return R.layout.fragment_login;
    }

    @Override
    public LoginPresenter createPresenter() {
        return loginPresenter;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //presenter.execute(new LoginRequest());
        mGetCodeLayout=new GetCodeLayout(getActivity(),this);

    }
    private AbortableFuture<LoginInfo> loginRequest;
    @Override
    public void onSuccess(final LoginResponse response) {
        String userId=response.getData().getUserId();
        String token=response.getData().getToken();
        String psd= Md5Util.md5Hex(token).toLowerCase();
        if (loginRequest != null) {
            loginRequest.abort();
            onLoginDone();
        }
        //执行云信登录
        loginRequest=NimUIKit.login(new LoginInfo(userId, psd), new RequestCallback<LoginInfo>() {
            @Override
            public void onSuccess(LoginInfo param) {
                LogUtil.i("NIM", "login success");

                onLoginDone();
                //发送登录成功，消息界面需要更新消息
                EventBus.getDefault().post(new LoginSuccessEvent());
                DemoCache.setAccount( param.getAccount());
                saveLoginInfo(param.getAccount(), param.getToken());

                // 初始化消息提醒配置
                initNotificationConfig();

                // 进入主界面
                onNimLoginSuccess(response);
            }

            @Override
            public void onFailed(int code) {
                onLoginDone();
                if (code == 302 || code == 404) {
                    ToastUtil.showToast(getActivity(),"帐号或密码错误");
                } else {
                    ToastUtil.showToast(getActivity(),"登录失败");
                }
            }

            @Override
            public void onException(Throwable exception) {
                ToastUtil.showToast(getActivity(),"登录异常");
                onLoginDone();
            }
        });


    }

    private void onNimLoginSuccess(LoginResponse response) {
        hideOpLoadingIndicator();
        User user=response.getData();
        UserRepo.getInstance().store(getActivity(),user);
        ActivityUtil.finish(getActivity());
    }

    private void initNotificationConfig() {
        // 初始化消息提醒
        NIMClient.toggleNotification(UserPreferences.getNotificationToggle());

        // 加载状态栏配置
        StatusBarNotificationConfig statusBarNotificationConfig = UserPreferences.getStatusConfig();
        if (statusBarNotificationConfig == null) {
            statusBarNotificationConfig = DemoCache.getNotificationConfig();
            UserPreferences.setStatusConfig(statusBarNotificationConfig);
        }
        // 更新配置
        NIMClient.updateStatusBarNotificationConfig(statusBarNotificationConfig);
    }

    private void saveLoginInfo(final String account, final String token) {
        Preferences.saveUserAccount(account);
        Preferences.saveUserToken(token);
    }
    private void onLoginDone() {
        loginRequest = null;
        hideOpLoadingIndicator();
    }
    @OnClick({R.id.layout_countdown,R.id.tv_login})
    public void onViewClcik(View v){
        switch (v.getId()){
            case R.id.layout_countdown:
                if (layout_phone.validate()) {
                    mGetCodeLayout.getCode(layout_phone.getText().toString());
                }else {
                    ToastUtil.showToast(getActivity(),"请输入正确的手机号");
                }

                break;
            case R.id.tv_login:
                if (validate()){
                    login();
                }
                break;
        }
    }

    private void login() {
        showOpLoadingIndicator();
        presenter.execute(buildLoginRequest());
    }

    private BaseRequest buildLoginRequest() {
        LoginRequest request=new LoginRequest();
        request.setPhone(layout_phone.getText().toString());
        request.setCode(et_code.getText().toString());
        return request;
    }

    private boolean validate() {
        if (!layout_phone.validate()){
            showError("请输入正确的手机号");
            return false;
        }

        return et_code.validate("请输入验证码");
    }

    @Override
    public void onGetCodeSuccess() {
        layout_countdown.startCountdown();
    }


}
